package com.example.mobifin_busticket.views.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mobifin_busticket.AppData;
import com.example.mobifin_busticket.BusTicketManagaer;
import com.example.mobifin_busticket.ComparatorForSorting;
import com.example.mobifin_busticket.MyApplication;
import com.example.mobifin_busticket.R;
import com.example.mobifin_busticket.Util;
import com.example.mobifin_busticket.controller.callbacks.ResponseListener;
import com.example.mobifin_busticket.controller.databasemanager.DatabaseManager;
import com.example.mobifin_busticket.models.Boarding_DropingPointModel;
import com.example.mobifin_busticket.models.BusModel;
import com.example.mobifin_busticket.models.FareDetailsModel;
import com.example.mobifin_busticket.models.FareModel;
import com.example.mobifin_busticket.models.FilterBusModel;
import com.example.mobifin_busticket.models.SourceModel;
import com.example.mobifin_busticket.views.adapter.CustomListAdapterForTrips;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.io.LineReader;

public class AvailableTripsActivity extends MobifinActivity implements
		android.view.View.OnClickListener {
	TextView tvSelectCity, tvJournyDate, tvFilter, tvTotalBus;

	ListView list;
	String strSourceID, strDestinationID, strDOJ, jdate, tvDate, from, to,
			serarchDate = null, selectedDate = null;
	SimpleDateFormat formateDate = new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat sdf = new SimpleDateFormat("EEE,dd MMM yyyy");
	boolean isTimefilter = false, isSeatfilter = false, isfarefilter = false;
	Button btn_bus_fare, btn_nxt_date, btn_prvs_date, btn_bus_seat,
			btn_bus_time, btn_back, btn_bus_filter, btn_filter_remove;
	CustomListAdapterForTrips tripAdapter;
	ArrayList<BusModel> busList;
	ArrayList<BusModel> templist;
	LinearLayout llfilter, llError, llChildError;
	DatabaseManager dbmanager = MyApplication.getDatabaseManagerInstance();
	int mLastFirstVisibleItem = -1;
	boolean isFailure = false, filterValue = false;
	FilterBusModel filterModel;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.available_trips_activity);
		filterModel = new FilterBusModel();
		tvSelectCity = (TextView) findViewById(R.id.slctCity);
		tvJournyDate = (TextView) findViewById(R.id.date);
		tvTotalBus = (TextView) findViewById(R.id.tvTotalBuses);
		tvFilter = (TextView) findViewById(R.id.tv_filterapply);
		list = (ListView) findViewById(R.id.searched_bus_List);
		llfilter = (LinearLayout) findViewById(R.id.ll_filter);
		llError = (LinearLayout) findViewById(R.id.ll_error_at_trip);
		llChildError = (LinearLayout) findViewById(R.id.ll_child_error_at_trip);
		btn_bus_filter = (Button) findViewById(R.id.btn_filter);
		btn_filter_remove = (Button) findViewById(R.id.btn_filterremove);
		btn_bus_fare = (Button) findViewById(R.id.btn_bus_fare);
		btn_nxt_date = (Button) findViewById(R.id.btn_nxt_date);
		btn_prvs_date = (Button) findViewById(R.id.btn_prvs_date);
		btn_bus_seat = (Button) findViewById(R.id.btn_bus_seats);
		btn_bus_time = (Button) findViewById(R.id.btn_bus_time);
		btn_back = (Button) findViewById(R.id.header_back_btn);
		tvFilter.setOnClickListener(this);
		btn_filter_remove.setOnClickListener(this);
		llError.setOnClickListener(this);
		btn_bus_filter.setOnClickListener(this);
		btn_bus_fare.setOnClickListener(this);
		btn_bus_time.setOnClickListener(this);
		btn_nxt_date.setOnClickListener(this);
		btn_prvs_date.setOnClickListener(this);
		btn_bus_seat.setOnClickListener(this);
		btn_back.setOnClickListener(this);
		btn_prvs_date.setVisibility(View.INVISIBLE);
		from = getIntent().getStringExtra("From");
		to = getIntent().getStringExtra("To");
		strSourceID = getIntent().getStringExtra("SouceID");
		strDestinationID = getIntent().getStringExtra("DestinationID");
		strDOJ = getIntent().getStringExtra("DOJ");
		tvTotalBus.setVisibility(View.GONE);
		System.out.println("ID:" + strSourceID + "\n" + strDestinationID + "\n"
				+ strDOJ);

		tvSelectCity.setText(from + " " + " to" + " " + to);

		getAllBus(strDOJ);
		list.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

				if (view.getId() == list.getId()) {

					final int currentFirstVisibleItem = list
							.getFirstVisiblePosition();
					mFilterScrollList(currentFirstVisibleItem);
					mLastFirstVisibleItem = currentFirstVisibleItem;
					mFilterScrollList(currentFirstVisibleItem);
				}

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				BusModel busModel = (BusModel) list.getAdapter().getItem(
						position);
				String Busid = busModel.getBus_id();
				AppData.BusId = Busid;
				AppData.SourceId = strSourceID;
				AppData.DestinationId = strDestinationID;
				String travelName = busModel.gettravels();
				String busType = busModel.getbusType();
				String departureTime = busModel.getdepartureTime();
				String arrivalTime = busModel.getarrivalTime();
				int totalSeat = busModel.getavailableSeats();
				Intent SeatIntent = new Intent(AvailableTripsActivity.this,
						SeatBoardingInfoActivity.class);
				SeatIntent.putExtra("BusId", Busid);
				SeatIntent.putExtra("TravelName", travelName);
				SeatIntent.putExtra("BusType", busType);
				SeatIntent.putExtra("DepartureTime", departureTime);
				SeatIntent.putExtra("ArrivalTime", arrivalTime);
				SeatIntent.putExtra("totalSeat", totalSeat);
				startActivity(SeatIntent);
			}
		});
	}

	private void mFilterScrollList(int currentFirstVisibleItem) {
		// TODO Auto-generated method stub

		if (currentFirstVisibleItem > mLastFirstVisibleItem) {
			if (!busList.equals(templist)) {
				llfilter.setVisibility(View.VISIBLE);
				tvFilter.setText(getResources().getString(
						R.string.btn_filterApply));
			} else {
				llfilter.setVisibility(View.GONE);
			}
			Log.d("scrool down", "scrool down");
		} else if (currentFirstVisibleItem < mLastFirstVisibleItem) {

			if (!busList.equals(templist)) {
				llfilter.setVisibility(View.VISIBLE);
				tvFilter.setText(getResources().getString(
						R.string.btn_filterApply));
			} else {
				llfilter.setVisibility(View.VISIBLE);
				tvFilter.setText(getResources().getString(
						R.string.filter_scroll));
				btn_filter_remove.setVisibility(View.GONE);
			}
			Log.d("scrool up", "scrool up");
		}

	}

	public void setSelctedDateinview(String selectedDate) {

		Date d;
		try {
			d = formateDate.parse(selectedDate);
			jdate = sdf.format(d);
			tvJournyDate.setText(jdate);
			tvDate = tvJournyDate.getText().toString();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getAllBus(String BusDOJ) {
		// TODO Auto-generated method stub
		setSelctedDateinview(BusDOJ);
		AppData.Source = from;
		AppData.Destination = to;
		AppData.DateOfJourny = tvDate;
		long date = System.currentTimeMillis();
		String currentDate = sdf.format(date);
		if (tvDate.equals(currentDate)) {
			btn_prvs_date.setVisibility(View.INVISIBLE);

		} else {
			btn_prvs_date.setVisibility(View.VISIBLE);
		}

		ResponseListener fetchAllTripsListener = new ResponseListener() {
			Animation slide = AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.slidedown);
			int noofField = 0;
			String errorMessage = "";

			@Override
			public void onResponse(Object busListresonse) {
				// printData(busListresonse);
				/*
				 * DatabaseManager dbmanager = new DatabaseManager(
				 * AvailableTripsActivity.this);
				 */
				busList = dbmanager.getBusListFromDB();
				if (busList.isEmpty()) {
					llError.startAnimation(slide);
					llError.setVisibility(View.VISIBLE);
					noofField = 1;
					errorMessage = AppData.NULLEROORAVAITRIP;
					Util.errorFieldcreationSeatselect(
							AvailableTripsActivity.this, llChildError,
							noofField, errorMessage);

				} else {

					tripAdapter = new CustomListAdapterForTrips(
							AvailableTripsActivity.this, busList);
					list.setAdapter(tripAdapter);
					tvTotalBus.setVisibility(View.VISIBLE);
					tvTotalBus.setText(busList.size()
							+ " "
							+ getResources().getString(
									R.string.searched_no_buses));
					templist = new ArrayList<BusModel>(busList);
				}
				// dbmanager.close();
			}
		};

		BusTicketManagaer busticketManager = new BusTicketManagaer();
		busticketManager
				.getAllTrips(AvailableTripsActivity.this,
						fetchAllTripsListener, AppData.CONSUMERKEY,
						AppData.SECRETKEY, AppData.BASESEATURL
								+ "/availabletrips?source=" + strSourceID
								+ "&destination=" + strDestinationID + "&doj="
								+ BusDOJ, "TRIPS");
	}

	protected void printData(Object busListresonse) {

		System.out
				.println("-------------------------in available trip activity-----------------------");
		ArrayList<BusModel> busList = (ArrayList<BusModel>) busListresonse;
		for (int i = 0; i < busList.size(); i++) {

			BusModel bm = busList.get(i);
			System.out
					.println("-------------------" + i + "bus---------------");
			System.out.println("busID:" + bm.getBus_id());
			System.out.println("BusID:" + busList.get(i).getBus_id());
			System.out.println("AC:" + busList.get(i).getACValue());
			System.out.println("Arraival Time:"
					+ busList.get(i).getarrivalTime());
			System.out.println("Available seat"
					+ busList.get(i).getavailableSeats());

			ArrayList<Boarding_DropingPointModel> boarding = busList.get(i)
					.getBoardingPointList();

			for (int j = 0; j < boarding.size(); j++) {
				System.out.println(j + "Boarding Points details for busID:"
						+ busList.get(i).getBus_id());

				System.out.println("Bus id in Boarding point:"
						+ boarding.get(0).getBusId());

				System.out.println("Boarding point id:"
						+ boarding.get(j).getBoardingPointId());
				System.out.println("Boarding Name :"
						+ boarding.get(j).getBordingPointName());
				System.out.println("Boarding Location:"
						+ boarding.get(j).getlocation());
				System.out.println("Boarding Prime:"
						+ boarding.get(j).getprime());
				System.out
						.println("Boarding Time:" + boarding.get(j).gettime());

			}

			System.out.println("Bus Type:" + busList.get(i).getbusType());
			System.out.println("Bus TypeId:" + busList.get(i).getbusTypeId());
			System.out.println("CancellationPolicy:"
					+ busList.get(i).getcancellationPolicy());
			System.out.print("Deprature Time:"
					+ busList.get(i).getdepartureTime());
			System.out.println("DOJ" + busList.get(i).getdoj());
			ArrayList<FareDetailsModel> fare = busList.get(i)
					.getFaredetailsList();
			System.out.println("=====In fare details====");
			for (int k = 0; k < fare.size(); k++) {
				System.out.println("Bus Fare" + fare.get(k).getbaseFare());
				System.out.println("Service tax Absolute:"
						+ fare.get(k).getserviceTaxAbsolute());
				System.out.println("Service tax percentage:"
						+ fare.get(k).getserviceTaxPercentage());
				System.out.println("Total fare:" + fare.get(k).gettotalFare());

			}
			ArrayList<FareModel> farelist = busList.get(i).getFareList();
			System.out.println("=====In fare ====");
			for (int k = 0; k < farelist.size(); k++) {
				System.out.println("Bus Fare" + farelist.get(k).getfare());

			}
			System.out.println("Id proof:"
					+ busList.get(i).getidProofRequired());
			System.out.println("Live Tracking:"
					+ busList.get(i).getliveTrackingAvailable());
			System.out.println("Non AC:" + busList.get(i).getnonAC());
			System.out.print("Operator:" + busList.get(i).getoperator());
			System.out.println("Partial Cancellation"
					+ busList.get(i).getpartialCancellationAllowed());
			System.out.println("Router Id:" + busList.get(i).getrouteId());
			System.out.println("Seater:" + busList.get(i).getseater());
			System.out.println("Sleeper:" + busList.get(i).getsleeper());
			System.out.println("Travel:" + busList.get(i).gettravels());
			System.out.print("Enabled Ticket:"
					+ busList.get(i).getmTicketEnabled());

		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.btn_nxt_date:
			next_date();
			getAllBus(strDOJ);
			break;
		case R.id.btn_prvs_date:
			prvs_date();
			break;
		case R.id.btn_bus_fare:
			OnfareClick();
			break;
		case R.id.btn_bus_time:
			OnTimeClick();
			break;
		case R.id.btn_bus_seats:
			OnSeatClick();
			break;
		case R.id.ll_error_at_trip:
			llError.setVisibility(View.GONE);
		case R.id.header_back_btn:
			finish();
			break;
		case R.id.tv_filterapply:
			if (!isFailure) {
				OnBusFilter();
			}
			break;
		case R.id.btn_filter:
			OnBusFilter();
			break;
		case R.id.btn_filterremove:
			OnFilterRemove();
			break;
		default:
			break;
		}
	}

	private void OnFilterRemove() {
		// TODO Auto-generated method stub
		//tvFilter.setVisibility(View.GONE);
		
		if (busList != null) {
			busList.clear();
			busList.addAll(templist);
			tvTotalBus.setText(busList.size() + " "
					+ getResources().getString(R.string.searched_no_buses));
			tripAdapter.notifyDataSetChanged();

			msetFilterProperty();
		}
	}

	@SuppressWarnings("deprecation")
	private void msetFilterProperty() {
		// TODO Auto-generated method stub
		btn_bus_filter.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.filter_icon));
		llfilter.setVisibility(View.GONE);
		filterValue = false;
		
		AppData.isAc = false;
		AppData.isNonAc = false;
		AppData.isNonSleeper = false;
		AppData.isSleeper = false;
		AppData.TravelResult = null;
		AppData.Boardingresult = null;
		AppData.Dropingresult = null;
		
		
	}

	private void OnBusFilter() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(AvailableTripsActivity.this,
				FilterBusActivity.class);
		intent.putExtra("Source Name", from);
		intent.putExtra("Destination Name", to);
		intent.putExtra("FilterValue", filterValue);
		intent.putExtra("Ac vale", AppData.isAc);
		intent.putExtra("NonAc vale", AppData.isNonAc);
		intent.putExtra("NonSleepreValue", AppData.isNonSleeper);
		intent.putExtra("Sleeper", AppData.isSleeper);
		intent.putStringArrayListExtra("TravelResult", AppData.TravelResult);
		intent.putStringArrayListExtra("BoardingResult", AppData.Boardingresult);
		intent.putStringArrayListExtra("DropingResult", AppData.Dropingresult);
		startActivityForResult(intent, 1);
		overridePendingTransition(R.anim.pull_up_from_bottom, R.anim.hold);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == 1) {
			llfilter.setVisibility(View.VISIBLE);
			btn_filter_remove.setVisibility(View.VISIBLE);
			tvFilter.setText(getResources().getString(R.string.btn_filterApply));
			String Ac = data.getStringExtra("AC");
			String NonAc = data.getStringExtra("NonAC");
			String Sleeper = data.getStringExtra("Sleeper");
			String NonSleeper = data.getStringExtra("NonSleeper");
			ArrayList<String> travel = data
					.getStringArrayListExtra("retuentravelList");
			ArrayList<String> boarding = data
					.getStringArrayListExtra("retuenBoardingList");
			ArrayList<String> droping = data
					.getStringArrayListExtra("retuenDropingList");

			ArrayList<BusModel> tempBuslist = new ArrayList<BusModel>();

			tempBuslist = dbmanager.getFilterSearch(Ac, NonAc, Sleeper,
					NonSleeper, travel, boarding, droping);

			if (tempBuslist.isEmpty()) {
				Toast.makeText(AvailableTripsActivity.this,
						"No Buses match your filter criteria", 1000).show();
				clearArrayInfoentity();
				busList.addAll(tempBuslist);
				tvTotalBus.setText(busList.size() + " "
						+ getResources().getString(R.string.searched_no_buses));
				tripAdapter.notifyDataSetChanged();
				tripAdapter.notifyDataSetInvalidated();
				btn_bus_filter.setBackgroundDrawable(getResources()
						.getDrawable(R.drawable.filter_icon_active));

				filterValue = false;

			} else {

				clearArrayInfoentity();

				busList.addAll(tempBuslist);
				tvTotalBus.setText(busList.size() + " "
						+ getResources().getString(R.string.searched_no_buses));
				;
				tripAdapter.notifyDataSetChanged();
				tripAdapter.notifyDataSetInvalidated();
				btn_bus_filter.setBackgroundDrawable(getResources()
						.getDrawable(R.drawable.filter_icon_active));

				filterValue = true;

			}
			if ((Ac.equals("false") || Ac.equals(""))
					&& (NonAc.equals("false") || NonAc.equals(""))
					&& (Sleeper.equals("false") || Sleeper.equals(""))
					&& (NonSleeper.equals("false") || NonSleeper.equals(""))
					&& travel == null && boarding == null && droping == null) {
				busList.addAll(templist);
				OnFilterRemove();
			}
		}
	}

	private void clearArrayInfoentity() {
		if (busList != null) {
			busList.clear();
		}
	}

	@SuppressWarnings("deprecation")
	private void OnTimeClick() {
		// TODO Auto-generated method stub
		btn_bus_time.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.middle_button_active));
		btn_bus_seat.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.button_bus_unselected_seat));
		btn_bus_fare.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.button_bus_unselected_fare));
		btn_bus_fare.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		btn_bus_seat.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		btn_bus_time.setTextColor(Color.WHITE);
		btn_bus_seat.setTextColor(Color.BLACK);
		btn_bus_fare.setTextColor(Color.BLACK);
		if (isTimefilter) {
			btn_bus_time.setCompoundDrawablesWithIntrinsicBounds(0, 0,
					R.drawable.filter_up_arrow, 0);
			isTimefilter = false;
			if (busList != null) {
				sortDescTime();
			}
		} else {
			btn_bus_time.setCompoundDrawablesWithIntrinsicBounds(0, 0,
					R.drawable.filter_down_arrow, 0);
			isTimefilter = true;
			if (busList != null) {
				sortAscTime();
			}
		}
	}

	private Date mconvertStringtoDate(String strDate) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm a");

		Date dateobj = null;
		try {
			dateobj = format.parse(strDate);
		} catch (ParseException e) {
			Log.d(AppData.ERROR, e.toString(), e);
		}
		return dateobj;
	}

	private void sortAscTime() {
		// TODO Auto-generated method stub
		Collections.sort(busList, new Comparator<BusModel>() {

			@Override
			public int compare(BusModel arg0, BusModel arg1) {
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				String strstartDate = sdf.format(mconvertStringtoDate(arg0
						.getdepartureTime()));
				String strendDate = sdf.format(mconvertStringtoDate(arg1
						.getdepartureTime()));
				return strstartDate.compareToIgnoreCase(strendDate);
			}
		});

		tripAdapter = new CustomListAdapterForTrips(
				AvailableTripsActivity.this, busList);
		list.setAdapter(tripAdapter);
		tripAdapter.notifyDataSetChanged();
		list.smoothScrollToPosition(0);
	}

	private void sortDescTime() {
		// TODO Auto-generated method stub
		Collections.sort(busList, new Comparator<BusModel>() {

			@Override
			public int compare(BusModel arg0, BusModel arg1) {
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				String strstartDate = sdf.format(mconvertStringtoDate(arg0
						.getdepartureTime()));
				String strendDate = sdf.format(mconvertStringtoDate(arg1
						.getdepartureTime()));
				return strendDate.compareToIgnoreCase(strstartDate);
			}
		});

		tripAdapter = new CustomListAdapterForTrips(
				AvailableTripsActivity.this, busList);
		list.setAdapter(tripAdapter);
		tripAdapter.notifyDataSetChanged();
		list.smoothScrollToPosition(0);
	}

	@SuppressWarnings("deprecation")
	public void OnSeatClick() {
		btn_bus_seat.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.right_button_active));
		btn_bus_fare.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.button_bus_unselected_fare));
		btn_bus_time.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.button_bus_unselected_time));

		btn_bus_time.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		btn_bus_fare.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		btn_bus_seat.setTextColor(Color.WHITE);
		btn_bus_fare.setTextColor(Color.BLACK);
		btn_bus_time.setTextColor(Color.BLACK);
		if (isSeatfilter) {
			btn_bus_seat.setCompoundDrawablesWithIntrinsicBounds(0, 0,
					R.drawable.filter_up_arrow, 0);
			isSeatfilter = false;
			if (busList != null) {
				desc_sort_bus_fare();
			}
		} else {
			btn_bus_seat.setCompoundDrawablesWithIntrinsicBounds(0, 0,
					R.drawable.filter_down_arrow, 0);
			isSeatfilter = true;
			if (busList != null) {
				asc_sort_bus_seat();
			}

		}
	}

	@SuppressWarnings("deprecation")
	public void OnfareClick() {
		btn_bus_fare.setBackgroundResource(R.drawable.left_button_active);
		btn_bus_time.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.button_bus_unselected_time));
		btn_bus_seat.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.button_bus_unselected_seat));
		btn_bus_fare.setTextColor(Color.WHITE);
		btn_bus_time.setTextColor(Color.BLACK);
		btn_bus_seat.setTextColor(Color.BLACK);

		btn_bus_time.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		btn_bus_seat.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		if (isfarefilter) {
			btn_bus_fare.setCompoundDrawablesWithIntrinsicBounds(0, 0,
					R.drawable.filter_up_arrow, 0);
			isfarefilter = false;
			if (busList != null) {
				desc_sort_bus_fare();
			}
		} else {
			btn_bus_fare.setCompoundDrawablesWithIntrinsicBounds(0, 0,
					R.drawable.filter_down_arrow, 0);
			isfarefilter = true;
			if (busList != null) {
				asc_sort_bus_fare();
			}

		}
	}

	private void asc_sort_bus_fare() {
		// TODO Auto-generated method stub
		Collections.sort(busList, new Comparator<BusModel>() {

			@Override
			public int compare(BusModel arg0, BusModel arg1) {
				// TODO Auto-generated method stub
				return (int) (arg0.getFareList().get(0).getfare() - arg1
						.getFareList().get(0).getfare());
			}
		});

		tripAdapter = new CustomListAdapterForTrips(
				AvailableTripsActivity.this, busList);
		list.setAdapter(tripAdapter);
		tripAdapter.notifyDataSetChanged();
		list.smoothScrollToPosition(0);
	}

	private void desc_sort_bus_fare() {
		// TODO Auto-generated method stub
		Collections.sort(busList, new Comparator<BusModel>() {

			@Override
			public int compare(BusModel arg0, BusModel arg1) {
				// TODO Auto-generated method stub
				return (int) (arg1.getFareList().get(0).getfare() - arg0
						.getFareList().get(0).getfare());
			}
		});

		tripAdapter = new CustomListAdapterForTrips(
				AvailableTripsActivity.this, busList);
		list.setAdapter(tripAdapter);
		tripAdapter.notifyDataSetChanged();
		list.smoothScrollToPosition(0);
	}

	private void asc_sort_bus_seat() {
		// TODO Auto-generated method stub

		Collections.sort(busList, new Comparator<BusModel>() {

			@Override
			public int compare(BusModel arg0, BusModel arg1) {
				// TODO Auto-generated method stub
				return (int) (arg0.getavailableSeats() - arg1
						.getavailableSeats());
			}
		});

		tripAdapter = new CustomListAdapterForTrips(
				AvailableTripsActivity.this, busList);
		list.setAdapter(tripAdapter);
		tripAdapter.notifyDataSetChanged();
		list.smoothScrollToPosition(0);

	}

	private void desc_sort_bus_seat() {
		// TODO Auto-generated method stub

		Collections.sort(busList, new Comparator<BusModel>() {

			@Override
			public int compare(BusModel arg0, BusModel arg1) {
				// TODO Auto-generated method stub
				return (int) (arg1.getavailableSeats() - arg0
						.getavailableSeats());
			}
		});

		tripAdapter = new CustomListAdapterForTrips(
				AvailableTripsActivity.this, busList);
		list.setAdapter(tripAdapter);
		tripAdapter.notifyDataSetChanged();
		list.smoothScrollToPosition(0);

	}

	public void next_date() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date newDate = null;
		// String tvDate = tvJournyDate.getText().toString();
		String tvDate = strDOJ;
		if (busList != null) {
			try {
				newDate = dateFormat.parse(strDOJ);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			long timeadj = 24 * 60 * 60 * 1000;
			Date nextDate = new Date(newDate.getTime() + timeadj);
			strDOJ = dateFormat.format(nextDate);
			String selectedDate = strDOJ;
			// getAllBus(selectedDate);
			preNextJourneydate();
			msetFilterProperty();
			System.out.println("Next Date is:" + selectedDate);
		}
	}

	public void prvs_date() {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date newDate = null;
		String tvDate = strDOJ;
		try {
			newDate = dateFormat.parse(strDOJ);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		long timeadj = 24 * 60 * 60 * 1000;
		Date nextDate = new Date(newDate.getTime() - timeadj);
		strDOJ = dateFormat.format(nextDate);
		String selectedDate = strDOJ;

		getAllBus(selectedDate);

		System.out.println("Prvs Date is:" + selectedDate);
	}

	@SuppressWarnings("deprecation")
	private void preNextJourneydate() {
		// getAllseatLayout();
		msetFilterProperty();
		btn_bus_seat.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.button_bus_seats_selector));
		btn_bus_fare.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.button_bus_fare_selector));
		btn_bus_time.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.button_bus_time_selector));
		btn_bus_seat.setTextColor(Color.BLACK);
		btn_bus_fare.setTextColor(Color.BLACK);
		btn_bus_time.setTextColor(Color.BLACK);
		btn_bus_time.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		btn_bus_fare.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
		btn_bus_seat.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
	}
}
